import React, { useEffect, useState,useRef } from 'react'
import { Card,Button,Space,Modal,Input,Tree,Spin, message,Form } from 'antd';
import { reqRoles,reqRoleModify,reqRoleAdd } from '../../api/index';
import MyTable from './components/Table'
import { connect } from 'react-redux';

import { resetUser } from '../../redux/actions';
import { removeUser,getUser } from '../../utils/storageUtils';
import './Role.css'

/* 
  角色管理路由
*/
export default connect(state=>({user:state.user}),{resetUser})(function Role(props) {

  const {user}=props

  const [role,setRole] =useState({})
  const [data,setData] =useState([])
  const [changing,setChanging] =useState(false)
  const [defaultCheckedKeys,setDefaultCheckedKeys] =useState([])
  const [treeData,setTreeData] =useState([])
  const [modalInfo,setModalInfo] =useState({visible:false,type:''})

  const role_form = useRef()

  const getTreeData=(data)=>{
    let res=[{title:'平台权限',key:'root',children:[]}]
    let child=[
      {title:'首页',path:'/home',key:'0-0'},
      {title:'商品',key:'0-1',children:[
        {title:'品类管理',key:'0-1-0',path:'/category'},
        {title:'商品管理',key:'0-1-1',path:'/product'},
      ]},
      {title:'用户管理',path:'/user',key:'0-2'},
      {title:'角色管理',path:'/role',key:'0-3'},
      {title:'图形图表',key:'0-4',children:[
        {title:'柱形图',key:'0-4-0',path:'/charts/bar'},
        {title:'折线图',key:'0-4-1',path:'/charts/line'},
        {title:'饼图',key:'0-4-2',path:'/charts/pie'},
      ]}
    ]
    let root_children=res[0].children
    let CheckedKeys =[]
    child.forEach(item=>{
      if(!item.children){
        if(data.includes(item.path)){
          CheckedKeys.push(item.key)
        }
      }else{
        item.children.forEach(i=>{
          if(data.includes(i.path)){
            CheckedKeys.push(i.key)
          }
        })
      }
      root_children.push(item)
    })
    setTreeData(res)
    setDefaultCheckedKeys(CheckedKeys)
    return res
  }
  
  const title=(
    <Space>
      <Button type='primary' onClick={()=>setModalInfo({visible:true,type:'create'})}>创建角色</Button>
      <Button type='primary' disabled={!role._id} onClick={()=>setModalInfo({visible:true,type:'set'})}>设置角色权限</Button>
    </Space>
  )

  const changeRole=()=>{
    if(modalInfo.type==='create'){
      role_form.current.validateFields().then(async values=>{
        let res=await reqRoleAdd(values)
        setModalInfo({visible:false,type:''})
        setData([])
        message.success(res.msg)
      })
      return
    }
    setChanging(true)
    setModalInfo({visible:false,type:''})
    let roles=[]
    const checkList={
      '0-0':'/home',
      '0-1-0':'/category',
      '0-1-1':'/product',
      '0-2':'/user',
      '0-3':'/role',
      '0-4-0':'/charts/bar',
      '0-4-1':'/charts/line',
      '0-4-2':'/charts/pie',
    }
    defaultCheckedKeys.forEach(i=>{
      if(checkList[i]){
        roles.push(checkList[i])
      }
    })
    let params={id:role._id,menus:roles}
    if(!role.auth_name){
      let auth=data.find(i=>i._id===user.role_id)
      params.auth_name=auth.name
      params.auth_time=new Date()
    }
    setDefaultCheckedKeys([...defaultCheckedKeys])
    reqRoleModify(params).then(res=>{
      if(res.data._id){
        setChanging(false)
        setData([])
        let isSelfRole=getUser().role_id===res.data._id
        message.success(res.msg+(isSelfRole?'，当前用户的权限改变需重新登录':''))
        if(isSelfRole){
          props.resetUser()
          removeUser()
          window.location.reload()
        }
        
      }
      
    }).catch(err=>{
      setChanging(false)
      message.error(err)
    })
  }

  useEffect(()=>{
    async function getData(){
      let res=await reqRoles()
      setData(res)
    }
    if(data.length===0)getData()
    if(role._id)getTreeData(role.menus)
  },[data,role])

  return (
    <Spin tip='正在修改...' spinning={changing}>
      <Card title={title}>
        <MyTable role={role} setRole={setRole} data={data}></MyTable>
        <Modal title={modalInfo.type==='create'?'创建角色':'设置角色权限'} onOk={changeRole} visible={modalInfo.visible} onCancel={()=>setModalInfo({visible:false,type:''})}>
          {
            modalInfo.type==='create'?(
              <Form ref={role_form}>
                <Form.Item name='name' label='角色名称' colon required  >
                  <Input placeholder='请输入角色名称'></Input>
                </Form.Item>
              </Form>
              
            ):(
              <>
                <Space align='center' style={{width:'100%',marginBottom:'10px'}}>
                  <div>角色名称：</div>
                  <Input disabled value={role.name}></Input>
                </Space>
                <Space style={{width:'100%',marginLeft:'20px'}}>
                  <Tree key={role._id} checkable 
                  onCheck={checkedKeys=>setDefaultCheckedKeys(checkedKeys)} 
                  treeData={treeData} defaultCheckedKeys={defaultCheckedKeys} 
                  defaultExpandAll />
                </Space>
              </>
            )
          }
        </Modal>
      </Card>
    </Spin>
    
  )
})
